import React, { useEffect, useRef, useCallback } from "react";
import NewPerson from "./NewPerson";
import Message from "./Message";
import PicMessage from "./PicMessage";
import {
    NEW_FILE,
    NEW_PERSON,
} from "../tools/msgType";

interface ChatZoneProps{
    msgList: NewMsg[];
}

function ChatZone(props: ChatZoneProps){

    const { msgList } = props;
    const wrapperRef = useRef<HTMLDivElement>(null);

    const scrollBottom = useCallback(() => {
        // 有新的信息发过来时就将视图往下移动
        wrapperRef.current?.scrollTo(0, wrapperRef.current.clientHeight);
    }, []);

    useEffect(() => {
        scrollBottom();
    }, [msgList.length, scrollBottom]);

    return (
        <div className="mb-3 h-75 flex-column" ref={wrapperRef} style={{overflowY: "auto"}}>
            {msgList.map((item,idx) => {
                switch(item.type){
                    case NEW_FILE: return <PicMessage key={idx} data={item} scrollBottom={scrollBottom} />
                    case NEW_PERSON: return <NewPerson key={idx} data={item} scrollBottom={scrollBottom} />
                    default: return <Message key={idx} data={item} scrollBottom={scrollBottom} />
                }
            })}
        </div>
    );
}

export default ChatZone;